<template>
  <div class="payment-page">
    <div class="container">
      <!-- 顶部倒计时提示 -->
      <div class="countdown-bar">
        <el-alert
          :title="`请在${minutes}:${seconds < 10 ? '0' : ''}${seconds}内完成支付，超时订单将自动取消`"
          type="warning"
          show-icon
          :closable="false"
        />
      </div>

      <!-- 订单信息 -->
      <div class="order-info">
        <h2>订单信息</h2>
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span class="value">{{ orderInfo.order?.orderNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">支付金额：</span>
          <span class="value price">¥{{ orderInfo.order?.payAmount?.toFixed(2) }}</span>
        </div>
        <div class="info-item">
          <span class="label">商品总额：</span>
          <span class="value">¥{{ orderInfo.order?.itemAmount?.toFixed(2) }}</span>
        </div>
        <div class="info-item">
          <span class="label">运费：</span>
          <span class="value">¥{{ orderInfo.order?.freightAmount?.toFixed(2) }}</span>
        </div>
        <div class="info-item">
          <span class="label">优惠金额：</span>
          <span class="value">¥{{ orderInfo.order?.discountAmount?.toFixed(2) }}</span>
        </div>
        <div class="info-item">
          <span class="label">收货信息：</span>
          <span class="value">{{ formatAddress(orderInfo.order) }}</span>
        </div>
        <div class="info-item">
          <span class="label">下单时间：</span>
          <span class="value">{{ formatDate(orderInfo.order?.createTime) }}</span>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="order-items">
        <h3>商品信息</h3>
        <div class="item-list">
          <div v-for="item in orderInfo.orderItems" :key="item.id" class="item">
            <el-image :src="item.itemImage" :alt="item.itemName" class="item-image" />
            <div class="item-info">
              <div class="item-name">{{ item.itemName }}</div>
              <div class="item-price">
                <span class="price">¥{{ item.price?.toFixed(2) }}</span>
                <span class="quantity">x{{ item.quantity }}</span>
                <span class="total">小计：¥{{ item.totalPrice?.toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="confirmPayment">跳转至{{paymentMethod === 'alipay' ? '支付宝' : '微信'}}支付</el-button>
        <el-button @click="cancelPayment">取消支付</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getOrderById, payOrder } from '@/api/order'
 
const router = useRouter()
const route = useRoute()

// 订单相关数据
const orderInfo = ref({
  order: null,
  orderItems: []
})
const paymentMethod = ref('alipay')

// 倒计时相关
const totalSeconds = ref(15 * 60) // 15分钟
const minutes = ref(15)
const seconds = ref(0)
let timer = null

// 支付二维码
const paymentQrCode = ref('/images/payment/pay.jpg')

// 格式化地址
const formatAddress = (order) => {
  if (!order) return ''
  return `${order.recipientName} ${order.recipientPhone} ${order.province}${order.city}${order.district}${order.addressDetail}`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 初始化数据
onMounted(async () => {
  // 从路由参数获取订单ID
  const { id, method } = route.query
  if (!id) {
    ElMessage.error('订单信息不完整')
    router.push('/cart')
    return
  }

  paymentMethod.value = method || 'alipay'
  paymentQrCode.value = `/public/images/payment/pay.jpg`

  try {
    // 调用订单查询接口获取订单详情
    const res = await getOrderById(id)
    if (!res) {
      ElMessage.error('获取订单信息失败')
      router.push('/user/orders')
      return
    }
    
    orderInfo.value = res

    // 启动倒计时
    startCountdown()
  } catch (error) {
    console.error('获取订单信息失败：', error)
    ElMessage.error('获取订单信息失败')
    router.push('/user/orders')
  }
})

// 清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 倒计时逻辑
const startCountdown = () => {
  timer = setInterval(() => {
    if (totalSeconds.value <= 0) {
      clearInterval(timer)
      ElMessage.warning('支付超时，订单已取消')
      router.push('/user/orders')
      return
    }

    totalSeconds.value--
    minutes.value = Math.floor(totalSeconds.value / 60)
    seconds.value = totalSeconds.value % 60
  }, 1000)
}

// 确认支付
const confirmPayment = async () => {
  if (paymentMethod.value === 'alipay') {
    try {
      if (!orderInfo.value.order?.id) {
        ElMessage.error('订单信息不完整')
        return
      }
      const orderId = Number(orderInfo.value.order.id);
      console.log('orderId:', orderId);
      console.log('order:', orderInfo.value.order);
      // const res = await payOrder(orderId)
      window.location.href = `http://localhost:8080/api/alipay/pay?orderId=${orderId}`
    } catch (error) {
      console.error('支付失败：', error)
      ElMessage.error('支付失败，请重试')
    }
  } else if (paymentMethod.value === 'wechat') {
    ElMessage.call('微信支付功能还没实现哦')
    return
  }
}
// 取消支付
const cancelPayment = () => {
  ElMessage.info('您已取消支付，可以在订单列表中继续支付')
  router.push('/user/orders')
}
</script>

<style lang="scss" scoped>
.payment-page {
  padding: 40px 0;
  background-color: #f5f5f5;
  min-height: calc(100vh - 200px);
}

.container {
  width: 800px;
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.countdown-bar {
  margin-bottom: 30px;
}

.order-info {
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;

  h2 {
    font-size: 24px;
    margin-bottom: 20px;
    color: #ff4d4f;
  }

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    .label {
      width: 100px;
      color: #666;
    }

    .value {
      flex: 1;
      color: #333;

      &.price {
        font-size: 24px;
        color: #ff4d4f;
        font-weight: bold;
      }
    }
  }
}

.order-items {
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;

  h3 {
    font-size: 20px;
    margin-bottom: 20px;
    color: #333;
  }

  .item-list {
    .item {
      display: flex;
      padding: 15px;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      margin-bottom: 15px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        border-color: #ff4d4f;
      }

      &:last-child {
        margin-bottom: 0;
      }

      .item-image {
        width: 80px;
        height: 80px;
        object-fit: cover;
        margin-right: 15px;
        border-radius: 4px;
      }

      .item-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .item-name {
          font-size: 14px;
          color: #333;
          margin-bottom: 8px;
        }

        .item-price {
          display: flex;
          align-items: center;
          gap: 15px;

          .price {
            color: #ff4d4f;
            font-weight: bold;
          }

          .quantity {
            color: #666;
          }

          .total {
            color: #666;
            font-size: 14px;
          }
        }
      }
    }
  }
}

.payment-section {
  text-align: center;
  margin-bottom: 40px;

  h3 {
    font-size: 20px;
    margin-bottom: 30px;
    color: #333;
  }

  .qr-code-container {
    .qr-code {
      width: 200px;
      height: 200px;
      margin-bottom: 20px;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      padding: 10px;
      background: #fff;
    }

    .scan-tip {
      font-size: 16px;
      color: #666;
    }
  }
}

.action-buttons {
  text-align: center;
  margin-top: 30px;

  .el-button {
    margin: 0 10px;
    padding: 12px 30px;
    font-size: 16px;

    &--primary {
      background-color: #ff4d4f;
      border-color: #ff4d4f;

      &:hover {
        background-color: #ff7875;
        border-color: #ff7875;
      }
    }
  }
}
</style>
